<template>
    <div>
        <a-modal :title="modal.title" width="auto" class="custom-modal" :confirmLoading="submitLoading" :visible="modal.visible" :footer="null" :closable="false">
            <div class="sign-modal-main">
                <div class="sign-modal-form">
                    <a-form layout="vertical" :form="enevt_form">
                        <a-form-item label="关联园区">
                            <a-select placeholder="请选择关联园区" 
                            :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                            show-search 
                            @change="parkOrTempChange"
                            :filter-option="filterOption"
                             v-decorator="['sourceId',{rules: [{ required: true, message: '请选择关联园区!' }]}]">
                                <a-select-option v-for="(item,key) in sourceIdData" :key="key" :value="item.parkId">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label="签约方式">
                            <a-select placeholder="请选择签约方式" @change="signChange" :getPopupContainer="(triggerNode) => triggerNode.parentNode" show-search v-decorator="['type',{rules: [{ required: true, message: '请选择签约方式!' }]}]">
                                <a-select-option v-for="(item,key) in signStateData" :key="key" :value="item.no">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label="服务协议类型（园区关联）">
                            <a-select placeholder="请选择服务协议类型" :getPopupContainer="(triggerNode) => triggerNode.parentNode" show-search v-decorator="['tempId',{rules: [{ required: !flag?true:false, message: '请选择服务协议类型!' }]}]">
                                <a-select-option v-for="(item,key) in tempData" :key="key" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label="签约名单" style="position: relative;">
                            <a-upload
                                v-decorator="['file']"
                                :file-list="fileList"
                                :before-upload="beforeUpload"
                                :remove="handleUploadRemove"
                                :customRequest="handlePrivew">
                                <a-button icon="upload">上传签约名单</a-button>
                            </a-upload>
                            <a-button icon="download" style="position: absolute;top:-8px;left: 160px;" @click="$store.dispatch('allGetSginExeclTemp')" class="ant-btn-warning">下载签约模板</a-button>
                        </a-form-item>
                    </a-form>
                    <div class="sign-remarks" style="padding: 20px 0 0;">
                        <h3 class="sign-title" style="font-size: 20px;font-weight: 600;color: #e6a23c;">当前签约队列人数：{{signNum}}</h3>
                    </div>
                    <div class="sign-remarks">
                        <h3 class="sign-title">注意事项说明：</h3>
                        <ul>
                           <li>A. 个人年龄 => 18周岁 <= 65周岁</li>
                            <li>B. 姓名、身份证号必须一致</li>
                            <li>C. 为保证及时到账，银行建议中、农、建、商业银行</li>
                            <li>D. 上传表格条数不要超1000条</li>
                            <li>E. 预览列表中有验证中和失败状态不能提交结算</li>
                            <li>F. 二要素校验若存在误判，则以银联校验数据为最终结果</li>
                        </ul>
                    </div>
                </div>
                <div class="sign-modal-table">
                    <a-spin tip="Loading..." :spinning="spinning">
                    <a-row>
                        <a-col :span="4">
                            <chart-card title="总笔数" :total="totalObj.total">
                                <a-button slot="action" type="primary" @click="queryTable('')" shape="circle" icon="search"></a-button>
                            </chart-card>
                        </a-col>
                         <a-col :span="5">
                            <chart-card title="正确名单笔数" :total="totalObj.success">
                                <a-button slot="action" type="primary" @click="queryTable(0)" shape="circle" icon="search"></a-button>
                            </chart-card>
                        </a-col>
                         <a-col :span="5">
                            <chart-card title="错误名单笔数" :total="totalObj.fail">
                                <a-button slot="action" type="primary" @click="queryTable(-1)" shape="circle" icon="search"></a-button>
                            </chart-card>
                        </a-col>
                         <a-col :span="5">
                            <chart-card title="验证中笔数" :total="totalObj.doing">
                            </chart-card>
                        </a-col>
                         <a-col :span="5">
                            <chart-card title="已签约笔数" :total="totalObj.signedCount">
                            </chart-card>
                        </a-col>
                    </a-row>
                    <a-alert
                        v-if="table.loadData.length > 0"
                        style="margin-bottom: 10px;"
                        type="info"
                        description="导入人员有认证失败的不能提交签约"
                        show-icon
                        closable>
                    </a-alert>
                    <a-button type="primary" @click="queryTable('')" style="margin-right:10px;" icon="reload">更新列表</a-button>
                    <span v-action:batchDelSignBtn>
                        <a-popconfirm
                        :title="`确定批量删除已签约用户，删除后不能恢复？`"
                        ok-text="确认"
                        cancel-text="关闭"
                        @confirm="batchDelSign()">
                            <a-button type="danger" icon="delete">批量删除已签约</a-button>
                        </a-popconfirm>
                    </span>
                    <a-table :columns="table.columns" 
                    :pagination="table.pagination" 
                    @change="handleTableChange" 
                    rowKey="id" 
                    :data-source="table.loadData">
                        <span slot="action" slot-scope="text, record">
                            <a @click="signUserEdit(record)">修改</a>
                            <a-divider type="vertical" />
                            <a-popconfirm
                            :title="`确定删除用户（${record.name}），删除后不能恢复？`"
                            ok-text="确认"
                            cancel-text="关闭"
                            @confirm="signUserDel(record)">
                                <a>删除</a>
                            </a-popconfirm>
                            <template v-if="record.errorType !== 0">
                                <a-divider type="vertical" />
                                <a-popconfirm
                                :title="`人工验证（${record.name}），是否验证通过！`"
                                ok-text="通过"
                                cancel-text="取消"
                                @confirm="apply(record)">
                                    <a>审核</a>
                                </a-popconfirm>
                            </template>
                           
                        </span>
                        <span slot="idCard" slot-scope="text, record">
                            <a-popover title="身份证号码" trigger="hover">
                                <template #content>
                                <p style="margin: 0;">{{record.idCard}}</p>
                                </template>
                                <a-button style="padding: 0;color:#000" type="link">{{record.idCard | filterMore(7)}}</a-button>
                            </a-popover>
                        </span>
                        <span slot="errorType" slot-scope="text, record">
                            <a-tag color="green" v-if="text===0">成功</a-tag>
                            <a-tag color="cyan" v-if="text===5">{{record.msg}}</a-tag>
                            <a-tag color="cyan" v-if="text===6">{{record.msg}}</a-tag>
                            <a-tag color="red" v-if="text===1">{{record.msg}}</a-tag>
                            <a-tag color="red" v-if="text===2">{{record.msg}}</a-tag>
                            <a-tag color="red" v-if="text===3">{{record.msg}}</a-tag>
                            <a-tag color="red" v-if="text===4">{{record.msg}}</a-tag>
                        </span>
                    </a-table>
                    </a-spin>
                </div>
            </div>
            <div class="ant-modal-footer">
                <a-popconfirm
                title="取消后，现有数据会丢失。是否取消！"
                ok-text="确认"
                cancel-text="关闭"
                @confirm="clearData">
                    <a-button key="back">取消</a-button>
                </a-popconfirm>
                <template v-if="table.loadData.length >=1">
                    <a-button type="primary" :disabled="modal.flagAuth" @click="handleSignSubmit">提交签约</a-button>
                </template>
            </div>
        </a-modal>
        <a-drawer
            title="修改二要素"
            :width="400"
            placement="right"
            :visible="userFormVisible">
            <a-form-model :model="userForm" ref="userForm">
                 <a-form-model-item label="真实姓名" prop="name" :rules="[{ required: true, message: '请输入真实姓名!' }]">
                    <a-input placeholder="请输入真实姓名号" v-model="userForm.name"/>
                </a-form-model-item>
                <a-form-model-item label="身份证号码" prop="idCard" :rules="[{ required: true, message: '请输入身份证号码!' },{validator: verifyIdCard}]">
                    <a-input placeholder="请输入身份证号码" v-model="userForm.idCard"/>
                </a-form-model-item>
                <a-form-model-item label="手机号码" prop="phone" :rules="[{ required: true, message: '请输入手机号码!' },{validator: verifyPhone}]">
                    <a-input placeholder="请输入手机号码" :maxLength="11" v-model="userForm.phone"/>
                </a-form-model-item>
            </a-form-model>
            <div class="custom-drawer-footer">
                <a-button style="margin-right: 8px" @click="userFormVisible=false">取消</a-button>
                <a-button type="primary" @click="handleSignUserSubmit('userForm')">提交修改</a-button>
            </div>
        </a-drawer>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
import store from '@/store'
import { ChartCard } from '@/components'
import { 
  allSignFileAnalysis,
  allGetSginRelation,
  getSignUserCount,
  allSignFilePreview,
  allSignUserEdit,
  allSignUserDel,
  batchDelSignUser,
  allSignSave,
  signErrorUserApply,
  getWaitCount
} from '@/api/manage/sign'
import {
    getEnterpriseOrParkEnabled,
    sysEnterpriseIdSignList
}from '@/api/manage/enterprise'
import {
  COLUMNS_SIGN_USER
} from './form'
import { checkIDCard,checkPhone} from '@/utils/util'
export default {
  name: 'UserSignAdd',
  components: {
    ChartCard
  },
  data () {
    return {
         userForm:{
            id:'',
            name:'',
            phone:'',
            idCard:''
        },
        userFormVisible:false,
        modal:{
            title:'新增签约',
            visible:false,
            flagAuth:true,
            signCode:'',
            errorType:''
        },
        fileList:[],
        sourceIdData:[],
        signStateData: [],
        tempData:[],
        totalObj:{
            total:0,
            success:0,
            fail:0,
            doing:0,
            signedCount:0
        },
        table:{
            columns:COLUMNS_SIGN_USER,
            loadData:[],
            pagination:{
                current:1,
                pageSize: 5,
                total:0,
                showSizeChanger: true,
					showQuickJumper: true,
                pageSizeOptions: ["5", "10", "20","30"],
                showTotal: total => `共有 ${total} 条数据`,
            }
        },
        timeCounter:null,
        submitLoading:false,
        flag:false,
        spinning:false,
        
        signNum: 0, // 当前签约队列人数
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  filters: {
    filterMore (value,num) {
      if (!value) return ''
      if (value.length > num) {
          return value.slice(0,num) + '...'
      }
      return value
    }
  },
  beforeCreate() {
    this.enevt_form = this.$form.createForm(this,{name:'enevt_form'});
  },
  methods:{
    add(){
        this.initClear();
        this.modal.visible = true;
        this.initParkSelect();
        this.initSignTypeSelect();
        this.getSignNum();
    },
    signChange(val){
        if(val === 4){
             this.enevt_form.setFieldsValue({
                tempId: '',
            });
        }
        this.flag = val === 4 ? true:false;
    },
    async initParkSelect(){
        let params = {enterpriseId:this.userInfo.relationId}
        const {data} = await store.dispatch('getEnterpriseOrParkEnabled',params);
        data && data.forEach(v=>{
            v.value = v.parkId;
            v.label = v.name;
        })
        this.sourceIdData = data;
    },
    async parkOrTempChange(parkId){
        const {data} = await allGetSginRelation(parkId);
        this.tempData = data.protocol;
    },
    async initSignTypeSelect(){
        const {data} = await sysEnterpriseIdSignList(this.userInfo.relationId);
        this.signStateData = data
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    beforeUpload(file, fileList) {
        const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        if (!isExcel) {
            this.$message.error('只能上传后缀 xlsx、xls格式!')
        }
        const isSize = file.size / 1024 / 1024 < 10
        if (!isSize) {
            this.$message.error('文件不得大于10MB!')
        }
        return isExcel && isSize
    },
    handleUploadRemove(file){
        this.enevt_form.setFieldsValue({
            file: '',
        });
        this.fileList.splice(0,1);
    },
    handlePrivew(info) {
        this.enevt_form.validateFieldsAndScroll(async(err, values) => {
            if (!err) {
                this.fileList = [info.file];
                let formData = new FormData();
                formData.append("relationId",values.sourceId);
                formData.append("file",info.file);
                const {code,data} = await allSignFileAnalysis(formData);
                if(code === '1'){
                    this.modal.signCode = data;
                    this.table.pagination.current = 1;
                    this.modal.errorType = '';
                    clearTimeout(this.timeCounter);
                    this.signList();
                }
            }else{
                return false;
            }
        });
    },
    queryTable(item){
        if(!this.modal.signCode){
            return this.$message.error('请上传签约名单!');
        }
       this.modal.errorType = item;
       this.table.pagination.current = 1;
       clearTimeout(this.timeCounter);
       this.signList();
    },
    settime(){
        let _this = this;
        _this.getSignCount();
        _this.timeCounter = setTimeout(function() {  
            _this.settime();
        },3000);  
    },
    async getSignNum() {
      const {code,data} = await getWaitCount();
      if (code == 1) {
        this.signNum = data
      }
    },
    async getSignCount(){
        const {code,data} = await getSignUserCount(this.modal.signCode);
        if(code === '1'){
            if(this.modal.errorType === -1){
                this.totalObj.success = 0;
                this.totalObj.doing = 0;
                this.totalObj.fail = data.fail;
                clearTimeout(this.timeCounter);
            }else if(this.modal.errorType === 0){
                 this.totalObj.success = data.success;
                 this.totalObj.fail = 0;
                 this.totalObj.doing = 0;
                 clearTimeout(this.timeCounter);
            }else{
                this.totalObj.success = data.success;
                this.totalObj.fail = data.fail;
                this.totalObj.doing = 0;
                let toTotal = parseInt(data.success) + parseInt(data.fail);
                if(this.totalObj.total >= 1){
                    this.totalObj.doing = parseInt(this.totalObj.total) - parseInt(toTotal);
                }
                if(this.totalObj.total >= 1 && this.totalObj.total === data.success){
                    this.modal.flagAuth = false;
                    clearTimeout(this.timeCounter);
                }else{
                    this.modal.flagAuth = true;
                }
            }
        }
    },
    async apply(item){
        let params = {id:item.id,code:this.modal.signCode};
        const {code} = await signErrorUserApply(params);
        if(code === '1'){
            clearTimeout(this.timeCounter);
            this.signList();
        }
    },
     async signUserDel(item){
        let params = {id:item.id};
        const {code} = await allSignUserDel(params);
        if(code === '1'){
            clearTimeout(this.timeCounter);
            this.signList();
        }
    },
    async batchDelSign(){
        if(this.table.loadData.length == 0){
            this.$message.error('请导入签约用户');
            return;
        }
        let params = {code:this.modal.signCode};
        const {code} = await batchDelSignUser(params);
        if(code === '1'){
            clearTimeout(this.timeCounter);
            this.signList();
        }
    },
    async signList(){
        let params = {};
        params.errorType = this.modal.errorType;
        params.code = this.modal.signCode;
        params.pageNum = this.table.pagination.current;
        params.pageSize = this.table.pagination.pageSize;
        this.spinning = true;
        const {code,data,signedCount} = await allSignFilePreview(params);
        this.spinning = false;
        if(code === '1'){
            this.table.loadData = data.content;
            this.table.pagination.total = data.total || 0;
            this.totalObj.total = data.total;
            this.totalObj.signedCount = signedCount
            this.settime();
        }
    },
    handleTableChange(pagination){
        this.table.pagination.current = pagination.current;
        this.table.pagination.pageSize = pagination.pageSize;
        this.signList();
    },
    signUserEdit(rows){
        this.userForm.id = rows.id;
        this.userForm.name = rows.name;
        this.userForm.phone = rows.phone;
        this.userForm.idCard = rows.idCard;
        this.userFormVisible = true;
    },
    verifyIdCard(rule,value, callback){
         if (value && !checkIDCard(value)) {
            callback('输入有误！');
        }
        callback()
    },
    verifyPhone(rule,value, callback){
        if (value && !checkPhone(value)) {
            callback('输入有误！');
        }
        callback()
    },
    handleSignUserSubmit(formName){
        this.$refs[formName].validate(async valid => {
        if (valid) {
          const { userForm } = this;
          let params = {};
          params.id = userForm.id;
          params.name = userForm.name;
          params.idCard = userForm.idCard;
          params.phone = userForm.phone;
          const {code} =  await allSignUserEdit(params);
          if(code === '1'){
            this.userFormVisible = false;
            clearTimeout(this.timeCounter);
            this.signList();
          }
        }else{
          return false;
        }
      });
    },
    async handleSignSubmit(){
        let params = {};
        const values = this.enevt_form.getFieldsValue();
        params.code = this.modal.signCode;
        params.sourceId = values.sourceId;
        params.tempId = values.tempId;
        params.type = values.type;
        this.submitLoading = true;
        const {code} =  await allSignSave(params);
        this.submitLoading = false;
        if(code === '1'){
        this.$message.success('操作成功');
        this.clearData();
        this.$emit("on-ok");
        }
    },
    initClear(){
        this.fileList = [];
        this.sourceIdData = [];
        this.signStateData = [];
        this.tempData = [];

        this.flag = false;
        this.modal.signCode = '';
        this.modal.errorType = '';
        this.modal.flagAuth = true;
        this.totalObj = {
            total:0,
            success:0,
            fail:0,
            doing:0
        }
        this.table.loadData = [];
        this.table.pagination.total = 0;
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 5;
        this.table.pagination.total = 0;
        this.userForm = {
            id:'',
            name:'',
            phone:'',
            idCard:''
        };
        this.enevt_form.resetFields();
        clearTimeout(this.timeCounter);
    },
    clearData(){
        this.modal.visible = false;
        clearTimeout(this.timeCounter);
    }
  }
}
</script>
<style>
.sign-modal-main{
    display: flex;background: #f5f5f5;
}
.sign-modal-form{
    width: 430px;background: #fff;padding:24px;
}
.sign-modal-table{
    flex: 1;margin-left: 10px;background: #fff;padding:20px
}
.sign-remarks{
    border-top: 1px solid rgba(0,0,0,.06);
    padding: 20px 0;
}
.sign-title{
    font-size: 14px;
    color: rgba(0,0,0,.85);
    font-weight: 500;
    margin-bottom: 20px;
}
.sign-remarks ul{
    margin: 0;
    padding:0;
    list-style-type: none;
}
.sign-remarks ul li{
    font-size: 14px;
    color: rgba(0,0,0,.45);
    margin-bottom: 6px;
}
.ant-modal-footer {
    padding: 10px 16px;
    text-align: right;
    background: transparent;
    border-radius: 0 0 4px 4px;
    border-top: 1px solid rgba(0,0,0,.06);
    height: 52px;
}
</style>